package com.example.h.weixinui3;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.view.View;
import android.widget.EditText;

import android.widget.Toast;
import com.example.h.dao.UserDao;
import com.example.h.entity.User;
import com.example.h.util.MyApplication;


public class LoginActivity extends AppCompatActivity {

    private EditText u_name,u_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        MyApplication.getInstance().addActivity(this);
        u_name=(EditText)findViewById(R.id.u_name);
        u_password=(EditText)findViewById(R.id.u_password);
    }

    public void login(View view){
        String name=u_name.getText().toString();
        String pwd=u_password.getText().toString();
        User user=new UserDao(this).login(name,pwd);
        if(user!=null){
            SharedPreferences sp=getSharedPreferences("lock",MODE_PRIVATE);
            SharedPreferences.Editor editor=sp.edit();
            editor.putString("LoginNo",user.getuId()+"");
            editor.putString("LoginName",user.getuName());
            editor.commit();
            Intent intent=new Intent(this,MainActivity.class);
            startActivity(intent);
        }else{
            Toast.makeText(this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
        }
    }
    public void back(View view){
        this.finish();
    }

    public void register(View view){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("用户注册");
        View dialogView=getLayoutInflater().from(this).inflate(R.layout.layout_register_user,null);
        final EditText uname=(EditText)dialogView.findViewById(R.id.u_name);
        final EditText upwd=(EditText)dialogView.findViewById(R.id.u_password);
        builder.setView(dialogView);
        builder.setPositiveButton("注册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                if (new UserDao(LoginActivity.this).addUser(new User(0,uname.getText().toString(),upwd.getText().toString()))){
                    Toast.makeText(LoginActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LoginActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
        builder.setNegativeButton("取消",null);
        builder.create().show();
    }
}
